package com.yihu.wlyy.web.doctor.account;

import java.net.URLDecoder;
import java.util.List;
import java.util.Map;

import com.yihu.wlyy.entity.*;
import com.yihu.wlyy.entity.address.Hospital;
import com.yihu.wlyy.entity.doctor.Doctor;
import com.yihu.wlyy.entity.doctor.DoctorComment;
import com.yihu.wlyy.entity.patient.Patient;
import com.yihu.wlyy.repository.PatientDao;
import com.yihu.wlyy.repository.TblBasicDao;
import com.yihu.wlyy.service.app.account.PatientInfoService;
import com.yihu.wlyy.service.app.consult.ConsultTeamService;
import com.yihu.wlyy.service.common.account.PatientService;
import com.yihu.wlyy.util.*;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springside.modules.utils.Encodes;

import com.yihu.wlyy.service.app.account.DoctorInfoService;
import com.yihu.wlyy.service.app.consult.DoctorCommentService;
import com.yihu.wlyy.service.app.hospital.HospitalService;
import com.yihu.wlyy.service.app.sign.FamilyContractService;
import com.yihu.wlyy.service.app.team.DrHealthTeamService;
import com.yihu.wlyy.service.common.account.TokenService;
import com.yihu.wlyy.web.BaseController;
import com.yihu.wlyy.entity.SbInfo;
import com.yihu.wlyy.repository.SbInfoDao;

/**
 * 用户注册的Controller.
 *
 * @author calvin
 */
@Controller
@RequestMapping(value = "/doctor")
public class DoctorController extends BaseController {

    @Autowired
    private DoctorInfoService doctorInfoService;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private DoctorCommentService doctorCommentService;
    @Autowired
    private DrHealthTeamService drHealthTeamService;
    @Autowired
    private FamilyContractService familyContractService;
    @Autowired
    private ConsultTeamService consultTeamService;
    @Autowired
    private HospitalService hospitalService;
    @Autowired
    private SbInfoDao sbInfoDao;
    @Autowired
    private PatientInfoService patientInfoService;
    @Autowired
    private PatientService patientService;
    @Autowired
    private PatientDao patientDao;
    @Autowired
    private TblBasicDao tblBasicDao;

    /**
     * 社区医院下医生列表查询接口 没分页
     *
     * @param hospital 医院标识
     * @return
     */
    @RequestMapping(value = "getDoctorsByhospitalNoPage")
    @ResponseBody
    public String getDoctorsByhospitalNoPage(
            @RequestParam(required = false) String hospital,
            @RequestParam(required = false) String name,
            @RequestParam(required = false) Integer type) {
        try {
            JSONArray array = new JSONArray();
            List<Map<String, Object>> list = familyContractService.getDoctorsByhospitalNoPage(hospital, name, type);
            if (list != null) {
                for (Map<String, Object> doctor : list) {
                    if (doctor == null) {
                        continue;
                    }
                    JSONObject json = new JSONObject();
                    json.put("id", doctor.get("id"));
                    // 医生标识
                    json.put("code", doctor.get("code"));
                    // 医生姓名
                    json.put("name", doctor.get("name"));
                    // 所在医院名称
                    json.put("hospital", doctor.get("hospital"));
                    // 所在医院名称
                    json.put("hospital_name", doctor.get("hospital_name"));
                    // 科室名称
                    json.put("dept_name", (doctor.get("dept_name") == null ||
                            StringUtils.isEmpty(doctor.get("dept_name").toString())) ? " " : doctor.get("dept_name"));
                    // 职称名称
                    json.put("job_name", (doctor.get("job_name") == null ||
                            StringUtils.isEmpty(doctor.get("job_name").toString())) ? " " : doctor.get("job_name"));
                    // 头像
                    json.put("photo", doctor.get("photo"));
                    // 简介
                    json.put("introduce", doctor.get("introduce"));
                    // 专长
                    json.put("expertise", doctor.get("expertise"));
                    array.put(json);
                }
            }
            return write(200, "获取医院医生列表成功！", "list", array);
        } catch (Exception e) {
            error(e);
            return error(-1, "获取医院医生列表失败！");
        }
    }

    /**
     * 社区医院下医生列表查询接口 有分页
     *
     * @param hospital 医院标识
     * @return
     */
    @RequestMapping(value = "getDoctorsByhospital")
    @ResponseBody
    public String getDoctorsByhospital(
            @RequestParam(required = false) String hospital,
            @RequestParam(required = false) Integer type,
            long id,
            int pagesize) {
        try {
            JSONArray array = new JSONArray();
            Page<Doctor> list = familyContractService.findDoctors(hospital, type, id, pagesize);
            if (list != null) {
                for (Doctor doctor : list) {
                    if (doctor == null) {
                        continue;
                    }
                    JSONObject json = new JSONObject();
                    json.put("id", doctor.getId());
                    // 医生标识
                    json.put("code", doctor.getCode());
                    // 医生姓名
                    json.put("name", doctor.getName());
                    // 所在医院名称
                    json.put("hospital_name", doctor.getHosptialName());
                    // 科室名称
                    json.put("dept_name", StringUtils.isEmpty(doctor.getDeptName()) ? " " : doctor.getDeptName());
                    // 职称名称
                    json.put("job_name", StringUtils.isEmpty(doctor.getJobName()) ? " " : doctor.getJobName());
                    // 头像
                    json.put("photo", doctor.getPhoto());
                    // 简介
                    json.put("introduce", doctor.getIntroduce());
                    // 专长
                    json.put("expertise", doctor.getExpertise());
                    array.put(json);
                }
            }
            return write(200, "获取医院医生列表成功！", "list", array);
        } catch (Exception e) {
            error(e);
            return error(-1, "获取医院医生列表失败！");
        }
    }

    /**
     * 社区医院列表查询接口
     *
     * @param type     医院类型：0全部，1大医院，2社区医院
     * @param province 患标识
     * @param city     城市标识
     * @param key      搜索关键字，用于搜索医院名称
     * @return
     */
    @RequestMapping(value = "hospitals")
    @ResponseBody
    public String hospitals(
            int type,
            @RequestParam(required = false) String province,
            @RequestParam(required = false) String city,
            @RequestParam(required = false) String town,
            @RequestParam(required = false) String key,
            long id,
            int pagesize) {
        try {
            JSONArray array = new JSONArray();
            Page<Hospital> list = familyContractService.findHospitals(type, province, city, town, key, id, pagesize);
            if (list != null) {
                for (Hospital hospital : list) {
                    if (hospital == null) {
                        continue;
                    }
                    JSONObject json = new JSONObject();
                    json.put("id", hospital.getId());
                    // 医院标识
                    json.put("code", hospital.getCode());
                    // 医院名称
                    json.put("name", hospital.getName());
                    // 省名
                    json.put("province_name", hospital.getProvinceName());
                    // 城市名
                    json.put("city_name", hospital.getCityName());
                    // 区县名
                    json.put("town_name", hospital.getTownName());
                    // 详细地址
                    json.put("address", hospital.getAddress());
                    // 简介
                    json.put("intro", hospital.getIntro());
                    // 医院图片
                    json.put("photo", hospital.getPhoto());
                    array.put(json);
                }
            }
            return write(200, "获取医院列表成功！", "list", array);
        } catch (Exception e) {
            error(e);
            return error(-1, "获取医院列表失败！");
        }
    }


    /**
     * 修改密码
     *
     * @param oldpwd 旧密码
     * @param newpwd 新密码
     * @return
     */
    @RequestMapping(value = "updatepwd")
    @ResponseBody
    public String updatepwd(String oldpwd, String newpwd) {
        try {
            Doctor doctor = doctorInfoService.findDoctorByCode(getUID());
            if (doctor == null) {
                return error(-1, "修改失败！");
            } else {
                String encodePWD = EncodesUtil.entryptPassword(Encodes.decodeHex(doctor.getSalt()), oldpwd);
                if (StringUtils.equals(doctor.getPassword(), encodePWD)) {
                    doctor.setPassword(newpwd);
                    doctorInfoService.updateDoctorPwd(doctor);
                    return success("修改成功！");

                } else {
                    return error(-1, "修改失败：旧密码错误！");
                }
            }
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "修改失败！");
        }
    }

    /**
     * 退出登录
     *
     * @return
     */
    @RequestMapping(value = "loginout")
    @ResponseBody
    public String loginout() {
        try {
            tokenService.delToken(2, getUID());
            return success("已成功退出！");
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "操作失败！");
        }
    }

    /**
     * 医生基本信息查询接口
     *
     * @return
     */
    @RequestMapping(value = "baseinfo")
    @ResponseBody
    public String baseinfo() {
        try {
            Doctor temp = doctorInfoService.findDoctorByCode(getUID());
            if (temp != null) {
                JSONObject json = new JSONObject();
                // 设置医生手机号码
                json.put("mobile", temp.getMobile());
                // 设置医生标识
                json.put("code", temp.getCode());
                // 设置医生姓名
                json.put("name", temp.getName());
                // 设置医生头像
                json.put("photo", CommonUtil.getPhoneUrl(temp.getPhoto()));
                // 设置医生性别
                json.put("sex", temp.getSex());
                // 设置省名称
                json.put("provinceName", temp.getProvinceName());
                // 设置城市名称
                json.put("cityName", temp.getCityName());
                // 设置医院名称
                json.put("hospitalName", temp.getHosptialName());
                // 设置部门名称
                json.put("deptName", StringUtils.isNotEmpty(temp.getDeptName()) ? temp.getDeptName() : "");
                // 设置职称
                json.put("jobName", StringUtils.isNotEmpty(temp.getJobName()) ? temp.getJobName() : "");
                // 设置医生专长
                json.put("expertise", StringUtils.isNotEmpty(temp.getExpertise()) ? temp.getExpertise() : "");
                // 设置医生简介
                json.put("introduce", StringUtils.isNotEmpty(temp.getIntroduce()) ? temp.getIntroduce() : "");
                // 二维码地址
                json.put("qrcode", temp.getQrcode());
                // 审核总数
                json.put("signed_amount", familyContractService.countAmountSigned(getUID()));
                // 等审核总数
                json.put("unsign_amount", familyContractService.countAmountUnsign(getUID()));
                // 咨询统计
                Map<String, Long> consultCount = consultTeamService.getAllCount(getUID());
                // 咨询总数
                json.put("consultAmount", consultCount.get("all"));
                // 当天咨询数
                json.put("consultAmountToday", consultCount.get("today"));
                //身份类型
                json.put("level", temp.getLevel().intValue());
                //身份证号
                json.put("idcard", temp.getIdcard());

                return write(200, "医生信息查询成功！", "data", json);
            } else {
                return error(-1, "医生信息查询失败！");
            }
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "医生信息查询失败！");
        }
    }

    /**
     * 医生基本信息查询接口
     *
     * @return
     */
    @RequestMapping(value = "baseinfoCount")
    @ResponseBody
    public String baseinfoCount(
            String doctorType) {
        try {
            Doctor temp = doctorInfoService.findDoctorByCode(getUID());
            if (temp != null) {
                JSONObject json = new JSONObject();
                // 审核总数
                if ("2".equals(doctorType)) {
                    //全科医生
                    json.put("signed_amount", familyContractService.countAmountSigned(getUID()));
                } else {
                    //健康管理师
                    json.put("signed_amount", familyContractService.countAmountSigned2(getUID()));
                }
                // 等审核总数
                json.put("unsign_amount", familyContractService.countAmountUnsign(getUID()));
                return write(200, "医生信息查询成功！", "data", json);
            } else {
                return error(-1, "医生信息查询失败！");
            }
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "医生信息查询失败！");
        }
    }

    /**
     * 患者基本信息保存
     *
     * @param photo     頭像
     * @param sex       性別
     * @param expertise 专长
     * @param introduce 简介
     * @param province  省标识
     * @param city      市标识
     * @return
     */
    @RequestMapping(value = "save")
    @ResponseBody
    public String save(
            @RequestParam(required = false) String photo,
            @RequestParam(required = false) Integer sex,
            @RequestParam(required = false) String expertise,
            @RequestParam(required = false) String introduce,
            @RequestParam(required = false) String province,
            @RequestParam(required = false) String city,
            @RequestParam(required = false) String mobile) {
        try {
            Doctor doctor = doctorInfoService.findDoctorByCode(getUID());

            if (StringUtils.isNotEmpty(mobile)) {
                if (!mobile.equals(doctor.getMobile())) {
                    if (doctorInfoService.findNormalByMobile(mobile) != null) {
                        return error(-2, "该手机号码已被注册！");
                    }
                    doctor.setMobile(mobile);
                }
            }
            // 设置头像
            if (StringUtils.isNotEmpty(photo)) {
                photo = CommonUtil.copyTempImage(photo);
                if (StringUtils.isNotEmpty(photo)) {
                    doctor.setPhoto(photo);
                }
            }
            // 设置性别
            if (sex != null) {
                doctor.setSex(sex);
            }
            // 设置生日
            // if (StringUtils.isNotEmpty(birthday)) {
            // doctor.setBirthday(DateUtil.strToDate(birthday, DateUtil.YYYY_MM_DD));
            // }
            // 设置医生专长
            if (StringUtils.isNotEmpty(expertise)) {
                doctor.setExpertise(expertise);
            }
            // 设置介绍内容
            if (StringUtils.isNotEmpty(introduce)) {
                doctor.setIntroduce(introduce);
            }
            // 设置省份标识
            if (StringUtils.isNotEmpty(province)) {
                doctor.setProvince(province);
            }
            // 设置城市标识
            if (StringUtils.isNotEmpty(city)) {
                doctor.setCity(city);
            }
            // 设置区县标识
            // if (StringUtils.isNotEmpty(town)) {
            // doctor.setTown(town);
            // }
            // 设置医院标识
            // if (StringUtils.isNotEmpty(hospital)) {
            // doctor.setHospital(hospital);
            // }
            // // 设置部门标识
            // if (StringUtils.isNotEmpty(dept)) {
            // doctor.setDept(dept);
            // }
            // // 设置职称
            // if (StringUtils.isNotEmpty(job)) {
            // doctor.setJob(job);
            // }
            if (doctorInfoService.updateDoctor(doctor) != null) {
                // 修改成功
                return write(200, "保存成功！", "data", doctor.getPhoto());
            } else {
                // 注册失败
                return error(-1, "保存失败！");
            }
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "保存失败！");
        }
    }

    /**
     * 红黄绿标患者数查询接口
     *
     * @return
     */
    @RequestMapping(value = "patients")
    @ResponseBody
    public String patients() {
        try {
            return write(200, "查询成功！", "data", familyContractService.amountPatients(getUID()));
        } catch (Exception e) {
            error(e);
            return error(-1, "查询失败！");
        }
    }

    /**
     * 患者评价查询接口
     *
     * @param id       最后一个id
     * @param pagesize 分页大小
     * @return
     */
    @RequestMapping(value = "comments")
    @ResponseBody
    public String comments(Integer id, Integer pagesize) {
        try {
            Page<DoctorComment> page = doctorCommentService.findByDoctor(getUID(), id, pagesize);
            JSONArray array = new JSONArray();
            if (page != null) {
                for (DoctorComment dc : page) {
                    if (dc == null) {
                        continue;
                    }
                    JSONObject json = new JSONObject();
                    // id
                    json.put("id", dc.getId());
                    // 评价人姓名
                    json.put("name", dc.getUname());
                    // 设置评价内容
                    json.put("content", dc.getContent());
                    // 评价星级
                    json.put("star", dc.getStar());
                    // 评价类型：1视频咨询评价、2图文咨询评价
                    json.put("type", dc.getType());
                    // 评价时间
                    json.put("czrq", DateUtil.dateToStrLong(dc.getCzrq()));
                    array.put(json);
                }
            }
            return write(200, "查询成功！", "list", page, array);
        } catch (Exception e) {
            error(e);
            return error(-1, "查询失败！");
        }
    }

//	 /**
//	 * 医生三师工作组查询接口
//	 * @return
//	 */
//	 @RequestMapping(value = "teams")
//	 @ResponseBody
//	 public String teams() {
//	 try {
//	 List<DoctorTeam> teams = doctorTeamService.getDoctorTeams(getUID());
//	 JSONArray array = new JSONArray();
//	 if (teams != null) {
//	 for (DoctorTeam team : teams) {
//	 if (team == null) {
//	 continue;
//	 }
//	 JSONObject json = new JSONObject();
//	 json.put("icon", team.getIcon());
//	 json.put("code", team.getCode());
//	 json.put("name", team.getName());
//	 json.put("doctor", team.getDoctorName());
//	 array.put(json);
//	 }
//	 }
//	 return write(200, "查询成功！", "list", array);
//	 } catch (Exception e) {
//	 error(e);
//	 return error(-1, "查询失败！");
//	 }
//	 }

    // /**
    // * 查询三师团队下的医生列表
    // * @param team
    // * @return
    // */
    // @RequestMapping(value = "team_members")
    // @ResponseBody
    // public String teamMembers(String team) {
    // try {
    // List<Doctor> members = doctorTeamService.findTeamMembersByCode(team);
    // JSONArray array = new JSONArray();
    // if (members != null) {
    // for (Doctor member : members) {
    // if (member == null) {
    // continue;
    // }
    // JSONObject json = new JSONObject();
    // json.put("photo", member.getPhoto());
    // json.put("code", member.getCode());
    // json.put("name", member.getName());
    // array.put(json);
    // }
    // }
    // return write(200, "查询成功！", "list", array);
    // } catch (Exception e) {
    // error(e);
    // return error(-1, "查询失败！");
    // }
    // }

    /**
     * 根据类别获取医院列表
     *
     * @param type
     * @param query    查询条件 医院名称
     * @param id
     * @param pageSize 页数
     * @return
     */
    @RequestMapping(value = "/hospital_list")
    @ResponseBody
    public String getHospitalList(
            @RequestParam(required = true) Integer type,
            @RequestParam(required = false) String query,
            @RequestParam(required = true) long id,
            @RequestParam(required = true) Integer pageSize) {
        try {

            Page<Hospital> hospitalList = hospitalService.getHospitalList(query, type, id, pageSize);

            JSONArray array = new JSONArray();
            if (hospitalList != null) {
                for (Hospital hospital : hospitalList) {
                    if (hospital == null) {
                        continue;
                    }
                    JSONObject json = new JSONObject();
                    json.put("id", hospital.getId());
                    json.put("code", hospital.getCode());
                    json.put("name", hospital.getName());
                    json.put("province", hospital.getProvince());
                    json.put("provinceName", hospital.getProvinceName());
                    json.put("city", hospital.getCity());
                    json.put("cityName", hospital.getCityName());
                    json.put("town", hospital.getTown());
                    json.put("townName", hospital.getTownName());
                    json.put("level", hospital.getLevel());
                    String levelName = "";
                    switch (hospital.getLevel()) {
                        case 1:
                            levelName = "医院";
                            break;
                        case 2:
                            levelName = "社区医院";
                            break;
                    }
                    json.put("levelName", levelName);
                    json.put("address", hospital.getAddress());
                    json.put("intro", hospital.getIntro());
                    json.put("photo", hospital.getPhoto());
                    array.put(json);
                }
            }
            return write(200, "查询成功！", "list", array);
        } catch (Exception ex) {
            error(ex);
            return error(-1, "查询失败！");
        }
    }

    /**
     * 邀请医生咨询
     *
     * @param patientCode
     * @param page
     * @param pageSize
     * @return
     */
    @RequestMapping(value = "/hospital_list_type")
    @ResponseBody
    public String getHospitalList(
            @RequestParam(required = true) int doctorType,
            @RequestParam(required = true) int consultType,
            @RequestParam(required = true) String patientCode,
            @RequestParam(required = false) String name,
            @RequestParam(required = true) Integer page,
            @RequestParam(required = true) Integer pageSize) {
        try {
            if (doctorType == 3) {
                //查找所有的全科医生
                Doctor doctor = doctorInfoService.getDoctor(consultType, patientCode);
                return null;
            } else if (doctorType == 2) {
                //查找所有的专科医生
                Page<Doctor> doctorList = doctorInfoService.getDoctorListByPatientCode(consultType, patientCode, name, page, pageSize);
                JSONArray array = new JSONArray();
                if (doctorList != null) {
                    for (Doctor doctor : doctorList) {
                        JSONObject json = new JSONObject();
                        json.put("id", doctor.getId());
                        json.put("code", doctor.getCode());
                        json.put("name", doctor.getName());
                        json.put("photo", doctor.getPhoto());
                        json.put("sex", doctor.getSex());
                        String sexName = "";
                        switch (doctor.getSex()) {
                            case 1:
                                sexName = "男";
                                break;
                            case 2:
                                sexName = "女";
                                break;
                        }
                        json.put("sexName", sexName);
                        json.put("job", doctor.getJob());
                        json.put("jobName", doctor.getJobName());
                        json.put("hospital", doctor.getHospital());
                        json.put("hospitalName", doctor.getHosptialName());
                        json.put("dept", doctor.getDept());
                        json.put("deptName", doctor.getDeptName());
                        array.put(json);
                    }
                }
                return write(200, "查询成功！", "list", array);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            error(ex);
            return error(-1, "查询失败！");
        }
        return null;
    }


    /**
     * 根据医院标识获取医生信息
     *
     * @param hospital 医院标识
     * @param query    查询条件 ：医生名称
     * @param id
     * @param pageSize 页数
     * @return
     */
    @RequestMapping(value = "/doctor_list")
    @ResponseBody
    public String getDoctorByHospital(
            @RequestParam(required = true) String hospital,
            @RequestParam(required = false) String query,
            @RequestParam(required = true) long id,
            @RequestParam(required = true) Integer pageSize) {

        try {
            Page<Doctor> doctorList = doctorInfoService.getDoctorListByHospital(query, hospital, id, pageSize);
            JSONArray array = new JSONArray();
            if (doctorList != null) {
                for (Doctor doctor : doctorList) {
                    if (hospital == null) {
                        continue;
                    }
                    JSONObject json = new JSONObject();
                    json.put("id", doctor.getId());
                    json.put("code", doctor.getCode());
                    json.put("name", doctor.getName());
                    json.put("photo", doctor.getPhoto());
                    json.put("sex", doctor.getSex());
                    String sexName = "";
                    switch (doctor.getSex()) {
                        case 1:
                            sexName = "男";
                            break;
                        case 2:
                            sexName = "女";
                            break;
                    }
                    json.put("sexName", sexName);
                    json.put("job", doctor.getJob());
                    json.put("jobName", doctor.getJobName());
                    json.put("hospital", doctor.getHospital());
                    json.put("hospitalName", doctor.getHosptialName());
                    json.put("dept", doctor.getDept());
                    json.put("deptName", doctor.getDeptName());
                    array.put(json);
                }
            }
            return write(200, "查询成功！", "list", array);
        } catch (Exception ex) {
            error(ex);
            return error(-1, "查询失败！");
        }

    }

    /**
     * 登录患者获取三师信息
     *
     * @return
     */
    @RequestMapping(value = "teachers")
    @ResponseBody
    public String teachers(String patient) {
        try {
            // 查询签约信息
            SignFamily signContract = familyContractService.findBySsPatient(patient);
            if (signContract == null) {
                return error(1, "无三师签约信息");
            }
            JSONObject doctorJson = new JSONObject();
            // 设置签约日期
            doctorJson.put("qyrq", DateUtil.dateToStr(signContract.getBegin(), DateUtil.YYYY_MM_DD));
            // 签约编号
            doctorJson.put("team_code", signContract.getTeamCode());
            // 查询三师医生信息
            List<Doctor> doctors = drHealthTeamService.findTeamDoctors(patient, 1);
            JSONArray jsonArray = new JSONArray();
            if (doctors != null) {
                for (Doctor doctor : doctors) {
                    if (doctor == null) {
                        continue;
                    }
                    JSONObject json = new JSONObject();
                    json.put("code", doctor.getCode());
                    json.put("name", doctor.getName());
                    json.put("photo", CommonUtil.getPhoneUrl(doctor.getPhoto()));
                    json.put("hospitalName", doctor.getHosptialName());
                    json.put("deptName", doctor.getDeptName());
                    json.put("jobName", doctor.getJobName());
                    json.put("expertise", doctor.getExpertise());
                    // 类型：1专科医生，2全科医生，3健康管理师
                    int type = doctor.getLevel();
                    if (type == 1) {
                        json.put("typename", "专科医生");
                    } else if (type == 2) {
                        json.put("typename", "全科医生");
                    } else if (type == 3) {
                        json.put("typename", "健康管理师");
                    } else {
                        json.put("typename", "");
                    }
                    jsonArray.put(json);
                }
            }
            doctorJson.put("list", jsonArray);
            return write(200, "查询成功！", "data", doctorJson);
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "查询失败！");
        }
    }

    /**
     * @param type 医生类别 1专科医生，2全科医生，3健康管理师
     * @return
     */
    @RequestMapping(value = "/doctor_combobox")
    @ResponseBody
    public String getDoctorCombobxByHospital(
            @RequestParam(required = true) String hospital,
            @RequestParam(required = false) String type) {

        try {

            List<Doctor> doctorList = doctorInfoService.getDoctorCombobxByHospital(type, hospital);

            JSONArray array = new JSONArray();
            if (doctorList != null) {
                for (Doctor doctor : doctorList) {
                    if (hospital == null) {
                        continue;
                    }
                    JSONObject json = new JSONObject();
                    json.put("id", doctor.getId());
                    json.put("code", doctor.getCode());
                    json.put("name", doctor.getName());
                    json.put("photo", doctor.getPhoto());
                    json.put("sex", doctor.getSex());
                    String sexName = "";
                    switch (doctor.getSex()) {
                        case 1:
                            sexName = "男";
                            break;
                        case 2:
                            sexName = "女";
                            break;
                    }
                    json.put("sexName", sexName);
                    json.put("job", doctor.getJob());
                    json.put("jobName", doctor.getJobName());
                    json.put("hospital", doctor.getHospital());
                    json.put("hospitalName", doctor.getHosptialName());
                    json.put("dept", doctor.getDept());
                    json.put("deptName", doctor.getDeptName());
                    array.put(json);
                }
            }
            return write(200, "查询成功！", "list", array);
        } catch (Exception ex) {
            error(ex);
            return error(-1, "查询失败！");
        }

    }

    /**
     * 患者端 专科医生列表
     *
     * @param name
     * @param paitentCode
     * @param page
     * @param pageSize
     * @return
     */
    @RequestMapping(value = "/doctor_1_list")
    @ResponseBody
    public String doctor_1_list(
            @RequestParam(required = false) String name,
            @RequestParam(required = false) String paitentCode,
            @RequestParam(required = true) Integer page,
            @RequestParam(required = true) Integer pageSize) {

        try {
            Page<Doctor> doctorList = doctorInfoService.getDoctorListByHospital(name, paitentCode, page, pageSize);
            JSONArray array = new JSONArray();
            if (doctorList != null) {
                for (Doctor doctor : doctorList) {
                    JSONObject json = new JSONObject();
                    json.put("id", doctor.getId());
                    json.put("code", doctor.getCode());
                    json.put("name", doctor.getName());
//					json.put("photo", doctor.getPhoto());
//					json.put("sex", doctor.getSex());
//					String sexName = "";
//					switch (doctor.getSex()) {
//						case 1:
//							sexName = "男";
//							break;
//						case 2:
//							sexName = "女";
//							break;
//					}
//					//json.put("sexName", sexName);
//					json.put("job", doctor.getJob());
//					json.put("jobName", doctor.getJobName());
                    json.put("hospital", doctor.getHospital());
                    json.put("hospitalName", doctor.getHosptialName());
//					json.put("dept", doctor.getDept());
//					json.put("deptName", doctor.getDeptName());
                    array.put(json);
                }
            }
            return write(200, "查询成功！", "list", array);
        } catch (Exception ex) {
            error(ex);
            return error(-1, "查询失败！");
        }
    }

    /**
     * 把专科医生拉到团队里面
     *
     * @param teamCode   团队code
     * @param doctor     专科医生code
     * @param sickNCode  慢病code
     * @param sickName   慢病名字
     * @param doctorName 专科医生名字
     * @return
     */
    @RequestMapping(value = "/doctor_1_Toteam")
    @ResponseBody
    public String doctor_1_Toteam(
            @RequestParam(required = false) String teamCode, //没用
            @RequestParam(required = true) String parientCode,
            @RequestParam(required = false) String groupCode,//没用
            @RequestParam(required = true) String doctor,
            @RequestParam(required = true) String doctorName,
            @RequestParam(required = true) String sickName,
            @RequestParam(required = true) String sickNCode) {
        try {
            doctorInfoService.doctor_1_Toteam(teamCode, doctor, doctorName, groupCode, super.getIMEI(), parientCode, sickName, sickNCode);

            return write(200, "成功！");
        } catch (Exception ex) {
            error(ex);
            return error(-1, "查询失败！");
        }
    }

    /**
     * 根据病人ID查找团队里面的全科医生
     *
     * @param parientCode 病人code
     * @return
     */
    @RequestMapping(value = "/getDoctor2ByParient")
    @ResponseBody
    public String getDoctor2ByParient(
            @RequestParam(required = true) String parientCode,
            @RequestParam(required = true) String consultCode) {
        try {
            Doctor doctor = doctorInfoService.getDoctor2ByParient(parientCode, consultCode);
            JSONObject json = null;
            if (doctor != null) {
                json = new JSONObject();
                json.put("code", doctor.getCode());
                json.put("name", doctor.getName());
                json.put("photo", doctor.getPhoto());
                json.put("id", doctor.getId());
                json.put("hospital", doctor.getHospital());
                json.put("hosptialName", doctor.getHosptialName());
            }
            return write(200, "查询成功！", "doctor", json);
        } catch (Exception ex) {
            error(ex);
            return error(-1, "查询失败！");
        }
    }

    /**
     * 根据病人ID查找所有的专科医生,如果团队有专科医生那么专科医生拍第一个
     *
     * @param parientCode 病人code
     * @return
     */
    @RequestMapping(value = "/getDoctor1ByParient")
    @ResponseBody
    public String getDoctor1ByParient(
            @RequestParam(required = true) String consultCode,
            @RequestParam(required = true) String parientCode,
            Integer page,
            Integer pageSize) {

        try {
            Map<String, Object> doctorList = doctorInfoService.getDoctor1ByParient(consultCode, parientCode, page, pageSize);
            JSONObject jo = new JSONObject();
            jo.put("totalPage", doctorList.get("totalPage"));
            jo.put("doctors", doctorList.get("doctors"));
            return write(200, "查询成功！", "data", jo);
        } catch (Exception ex) {
            error(ex);
            return error(-1, "查询失败！");
        }
    }

    /**
     * 验证患者的名字，身份证和医保卡
     *
     * @return
     */
    @RequestMapping(value = "/validatePatient")
    @ResponseBody
    public String validatePatient(
            @RequestParam(required = true) String name,
            @RequestParam(required = true) String idcard,
            @RequestParam(required = true) String ssc) {

        try {
            if (StringUtils.isEmpty(name)) {
                return error(-1, "姓名不允许为空");
            }
            if (StringUtils.isEmpty(idcard)) {
                return error(-1, "身份证号不允许为空");
            }
            if (StringUtils.isEmpty(ssc)) {
                return error(-1, "社保卡号不允许为空");
            }
            // 校验身份证号
            IdcardValidator validator = new IdcardValidator();
            if (validator.isValidatedAllIdcard(idcard)) {
                if (idcard.length() == 15) {
                    idcard = validator.convertIdcarBy15bit(idcard);
                    if (StringUtils.isEmpty(idcard)) {
                        return error(-1, "请输入正确的身份证号");
                    }
                }
            } else {
                return error(-1, "请输入正确的身份证号");
            }

            SbInfo sbInfo = sbInfoDao.findBySfzh18Max(idcard);
            if (sbInfo != null) {
                if (name.compareTo(sbInfo.getXming0() == null ? "" : sbInfo.getXming0()) != 0) {
                    return error(-1, "身份证号与姓名不一致，请检查后重新输入");
                }
                if (ssc.compareTo(sbInfo.getCardno() == null ? "" : sbInfo.getCardno()) != 0 && ssc.compareTo(sbInfo.getCard16() == null ? "" : sbInfo.getCard16()) != 0) {
                    return error(-1, "身份证号与医保卡号不一致，请检查后重新输入");
                }
            } else {
                return error(-1, "对不起，暂不支持16年6月份之后办理的医保卡注册");
            }
            return write(200, "查询成功！");
        } catch (Exception ex) {
            error(ex);
            return error(-1, "查询失败！");
        }
    }

    /**
     * 得到 健康咨询  签约消息 健康体征 重要通知 和讨论组的消息数目
     */
    @RequestMapping(value = "/getAllMessageNum")
    @ResponseBody
    public String getAllMessageNum(
            String doctorCode,
            String doctorType) {
        try {
            JSONObject json = new JSONObject();
//			if("2".equals(doctorType)){
//				//全科医生
//				json.put("healthConsult", doctor.getCode());//健康咨询
//				json.put("sign", doctor.getName());//签约消息
//				json.put("healthTZ", doctor.getPhoto());//健康体征
//				json.put("importantMessage", doctor.getId());//重要通知
//				json.put("groupMessage", doctor.getId());//讨论组消息
//			}else{
//				//健康管理师
//				json.put("healthConsult", doctor.getCode());//健康咨询
//				json.put("sign", doctor.getName());//签约消息
//				json.put("healthTZ", doctor.getPhoto());//健康体征
//				json.put("importantMessage", doctor.getId());//重要通知
//				json.put("groupMessage", doctor.getId());//讨论组消息
//			}
            return write(200, "查询成功！", "doctors", json);
        } catch (Exception ex) {
            error(ex);
            return error(-1, "查询失败！");
        }
    }

    /**
     * 根据身份证号
     *
     * @param idcard
     * @return
     */
    @RequestMapping(value = "/patient_cardno")
    @ResponseBody
    public String getPatientCardNo(String idcard) {
        try {
            String cardNo = "";
            Patient patient = patientInfoService.findByIdcard(idcard);
            if (patient == null || StringUtils.isEmpty(patient.getSsc())) {
                SbInfo sbInfo = sbInfoDao.findBySfzh18(idcard);
                if (sbInfo != null) {
                    cardNo = sbInfo.getCardno();
                }
            } else {
                cardNo = patient.getSsc();
            }

            return write(200, "查询成功!", "data", cardNo);
        } catch (Exception e) {
            e.printStackTrace();
            return error(-1, "查询失败!");
        }
    }

    /**
     * 根据level查找机构下的类别医生
     *
     * @param hospital
     * @param level
     * @return
     */
    @RequestMapping(value = "/findDoctorByLevelAndHospital")
    @ResponseBody
    public String findDoctorByLevelAndHospital(String hospital, Integer level) {
        try {
            List<Doctor> doctorList = doctorInfoService.findDoctorByLevelAndHospital(hospital, level);
            JSONArray array = new JSONArray();
            if (doctorList != null) {
                for (Doctor doctor : doctorList) {
                    JSONObject json = new JSONObject();
                    json.put("id", doctor.getId());
                    json.put("code", doctor.getCode());
                    json.put("name", doctor.getName());
                    array.put(json);
                }
            }
            return write(200, "查询成功!", "doctors", array);
        } catch (Exception e) {
            e.printStackTrace();
            return error(-1, "查询失败!");
        }
    }

    /**
     * 更新身份证号
     *
     * @param idcard
     * @return
     */
    @RequestMapping(value = "/idcard_update")
    @ResponseBody
    public String updateIdcard(String idcard) {
        try {
            if (StringUtils.isEmpty(idcard)) {
                return error(-1, "身份证号不能为空");
            }

            if (doctorInfoService.updateDoctorIdcard(idcard, getUID())) {
                return write(200, "更新成功");
            } else {
                return error(-1, "更新成功");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return error(-1, "更新失败");
        }
    }

    /**
     * 更新医生性别
     *
     * @param sex
     * @return
     */
    @RequestMapping(value = "/sex_update")
    @ResponseBody
    public String updateSex(int sex) {
        try {
            if(doctorInfoService.updateSex(sex,getUID())){
                return write(200, "更新成功");
            }else{
                return error(-1, "更新失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return error(-1, "更新失败");
        }
    }

    /**
     * 更新医生介绍
     *
     * @param introduce
     * @return
     */
    @RequestMapping(value = "/introduce_update")
    @ResponseBody
    public String updateIntroduce(String introduce) {
        try {
            if (StringUtils.isEmpty(introduce)) {
                return error(-1, "身份证号不能为空");
            }
            if(doctorInfoService.updateIntroduce(introduce,getUID())){
                return write(200, "更新成功");
            }else{
                return error(-1, "更新失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return error(-1, "更新失败");
        }
    }

    /**
     * 更新医生专长
     *
     * @param expertise
     * @return
     */
    @RequestMapping(value = "/expertise_update")
    @ResponseBody
    public String updateExpertise(String expertise) {
        try {
            if (StringUtils.isEmpty(expertise)) {
                return error(-1, "专长不能为空");
            }
            if(doctorInfoService.updateExpertise(expertise,getUID())){
                return write(200, "更新成功");
            }else{
                return error(-1, "更新失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return error(-1, "更新失败");
        }
    }

    /**
     * 设置给医生名医
     *
     * @param doctorCode 医生code
     * @param status     1 是 0否
     * @return
     */
    @RequestMapping(value = "/setFamous")
    @ResponseBody
    public String setFamous(String doctorCode, Integer status) {
        try {
            doctorInfoService.setFamous(doctorCode,status);
            return write(200, "更新成功");
        } catch (Exception e) {
            e.printStackTrace();
            return error(-1, "更新失败");
        }
    }
}
